import { reactive, ref } from 'vue'
import { ProductData, QueryProductData } from '@/api/chunfeng/product/interfaces'
import { UnwrapNestedRefs } from '@vue/reactivity'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { useProductApi } from '@/api/chunfeng/product'
import { useRouter } from 'vue-router'
import { Form } from 'ant-design-vue'

const { executeQueryRequest, executeCommandRequest } = useHttpRequest()
const { queryProduct, enableProduct, disableProduct } = useProductApi()

export const useProductQueryFunctions = () => {
  const csRef = ref()
  const bsRef = ref()
  const productDataSet = ref(Array<ProductData>())

  const paginationConfig = reactive({
    showSizeChanger: true,
  })

  const queryParams: UnwrapNestedRefs<QueryProductData> = reactive({
    name: undefined,
    categoryId: undefined,
    brandId: undefined,
    enabled: undefined,
  })

  // const { resetFields } = useForm(queryParams)
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '分类',
      dataIndex: 'category.name',
      key: 'categoryName',
    },
    {
      title: '品牌',
      dataIndex: 'brand.name',
      key: 'brandName',
    },
    {
      title: '主单位',
      dataIndex: 'primaryUnit.name',
      key: 'primaryUnitName',
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      slots: { customRender: 'enabled' },
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },

    {
      title: '操作',
      key: 'action',
      slots: { customRender: 'action' },
    },
  ]

  const { resetFields } = Form.useForm(queryParams, reactive({}))

  function enable(uid: string) {
    executeCommandRequest(enableProduct(uid), {
      message: '商品启用成功',
      callback: () => {
        query()
      },
    })
  }

  function disable(uid: string) {
    executeCommandRequest(disableProduct(uid), {
      message: '商品停用成功',
      callback: () => {
        query()
      },
    })
  }

  const router = useRouter()
  function edit(uid: string) {
    router.push({ path: '/product/edit', query: { productId: uid } })
  }

  function reset() {
    resetFields()
    csRef.value.reset()
    bsRef.value.reset()
  }

  function query() {
    productDataSet.value.length = 0
    executeQueryRequest(queryProduct(queryParams), (results: ProductData[]) => {
      productDataSet.value.push(...results)
    })
  }

  function doCategorySelected(value: string) {
    queryParams.categoryId = value
  }

  function doBrandSelected(value: string) {
    queryParams.brandId = value
  }

  return {
    productDataSet,
    queryParams,
    enable,
    disable,
    query,
    paginationConfig,
    columns,
    reset,
    edit,
    csRef,
    bsRef,
    doCategorySelected,
    doBrandSelected,
  }
}
